document.addEventListener('click', event => {
    showWindowForAddingBook(event);
    addNewBook(event);
    closeWindowForAddingBook(event);
})



function closeWindowForAddingBook(event) {
    if (!event.target.classList.contains('window-for-adding-book-wrapper')) return;

    document.querySelector('.window-for-adding-book-wrapper').remove();
}

function addNewBook(event) {
    if (!event.target.closest('[data-add-new-book]')) return;
    event.preventDefault();

    const url = document.location.origin + '/book/add/';
    const form = document.querySelector('[name="add-book"]');
    const token = form.querySelector('input[name="csrfmiddlewaretoken"]').value;
    const formData = new FormData(form);
    fetch(url, {
        method: 'POST',
        body: formData,
        headers: {'X-CSRFToken': token}
    })
}


function showWindowForAddingBook(event) {
    if (!event.target.closest('.add-book')) return;
    event.preventDefault();

    const url = document.location.origin + '/book/add/';
    const windowForAddingBook = getWindowForAddingBook();

    base.sendAjaxRequest(url, 'GET')
        .then(result => {
            console.log('res', result);
            insertData(result, windowForAddingBook);
        })
    

    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function insertData(data, windowForAddingBook) {
        const form = data['form'];
        windowForAddingBook.insertAdjacentHTML('beforeend', form)
        document.body.append(windowForAddingBook);
    }
}

function getWindowForAddingBook() {
    const window = document.createElement('div');
    window.className = 'window-for-adding-book-wrapper';
    return window;
}